package com.terrorism.first.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.terrorism.first.R;
import com.terrorism.first.adapter.HotOfCategoryAdapter;
import com.terrorism.first.model.HotOfCategoryModel;
import com.terrorism.first.server.HotOfCategoryConnect;
import com.terrorism.first.utils.Utils;


public class HomeFragment extends Fragment {

	ListView lvListHotOfCategory;
	HotOfCategoryAdapter adapter;
	
	List<HotOfCategoryModel> listData;
	
	Context mContext;
	
	int with;
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mContext = activity;
		with = Utils.getScreenWith(activity);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View v = inflater.inflate(R.layout.fragment_home, container, false);
		lvListHotOfCategory = (ListView) v.findViewById(R.id.lvListHotOfCategory);	
		listData  =new ArrayList<HotOfCategoryModel>();
		
		int imageWith = (with-Utils.convertTodp(mContext, 100))/3;
		adapter = new HotOfCategoryAdapter(listData,mContext);
		adapter.setWithOfImage(imageWith);
		lvListHotOfCategory.setAdapter(adapter);
		
		getData();
		return v;
	}
	Handler hander = new Handler(); 
	void getData()
	{
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				final JSONObject jsonObject = HotOfCategoryConnect.getHotOfCategory(mContext);
				hander.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
					
							int result;
							try {
								result = jsonObject.getInt(HotOfCategoryConnect.result);
							
							if(result==1)
							{
								listData.clear();
								listData.addAll(HotOfCategoryConnect.getHotOfCategoryFromJson(jsonObject));
								adapter.notifyDataSetChanged();
								Toast.makeText(mContext, "Success", 1000).show();
							}else
							{
								
							}
							
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
							
						
					}
				});
			}
		}).start();
	}
}

